package com.kbtd.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.kbtd.dto.UserDTO;
import com.kbtd.utils.UserHolder;
import com.kbtd.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.kbtd.constant.RedisConstants.*;
import static com.kbtd.constant.SystemConstants.LOGIN_HEADER;

/**
 * token拦截器（读取请求用户token信息)
 * @author wp
 * @version 1.0
 */
@Component
@Slf4j
public class TokenFlushInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(LOGIN_HEADER);

        if (StringUtils.hasLength(token)) {
            String tokenKey = RedisUtils.createKey(LOGIN_USER_KEY_PREFIX, token);
            Map<Object, Object> entries = stringRedisTemplate.
                    opsForHash().entries(tokenKey);

            UserDTO userDTO = new UserDTO();
            BeanUtil.fillBeanWithMap(entries, userDTO, false);
            UserHolder.saveUser(userDTO);

            stringRedisTemplate.expire
                    (tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        }

        log.info("登录权限token: " + token);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
